#include "texture.hpp"

#include <d3dx9tex.h>
#include "rendererdx.hpp"

namespace dexgel
{
	class TextureDX : public Texture
	{
	public:
		TextureDX()
		{
			mTexture = NULL;
		}

		virtual ~TextureDX()
		{
			// If we have a D3D texture resource, free it
			if(mTexture)
			{
				mTexture->Release();
				mTexture = NULL;
			}
		}


		virtual bool load(const std::string &filename)
		{
			// Error Check -- If device isn't valid return false
			if(!priv::RendererDx::mDevice) 
				return false; 

			// If a texture is already loaded, free it before we load a new one
			if(mTexture)
			{
				mTexture->Release();
				mTexture = NULL;
			}

			// D3D makes it VERY EASY for us to load a texture.  Lets look at 
			// this function by parameter:
			// CD3DObj::mDevice -- Pointer to a IDirect3DDevice9 (D3D display device)
			//					   that is to be associated with the texture
			// fileName -- The name of the texture file to load.  Valid texture file
			//			   extensions are:  .bmp, .dib, .dds, .jpg, .png, .tga
			// &mTexture -- The address of a pointer to a IDirect3DTexture9 (D3D texture
			//				   interface) that will be filled with the created texture resource
			return (D3DXCreateTextureFromFile(priv::RendererDx::mDevice , filename.c_str(), &mTexture) == D3D_OK);

			// **NOTE** This function creates a full mipmap chain.  So if your image, for instance, is 
			// 128x128 this will produce mipmaps of sizes 64x64, 32x32, 16x16, 8x8, 4x4, 2x2, and 1x1. 
		}

		virtual void select()
		{
			assert(priv::RendererDx::mDevice != NULL); // Make sure device is valid

			// So the real question is how do we tell D3D what texture to 
			// use when?  Well luckily to say "Hey use this texture for 
			// all of the next drawing operations until told otherwise" is 
			// a fairly simple thing to do.  By calling the SetTexture() method
			// from our D3D device we can set what texture we want to use
			// and for what texture stage we want to use it in.
			// So by parameter:
			// 0 -- The texture stage
			// mTexture -- The texture resource we want to select
			HRESULT result = priv::RendererDx::mDevice->SetTexture(0, mTexture);
			assert(result == D3D_OK);
		}
	private:
		IDirect3DTexture9 *mTexture;
	};
}